<template>
  <v-dialog>
    <div class="wrap-content">
      <!--新增收货地址-->
      <div class="title">
        <h2 v-if="isNewAdd === 1">{{$tc('message.addAddress', 1)}}</h2>
        <h2 v-else>{{$tc('message.modifyAddress')}}</h2>
      </div>
      <div class="content">
      	<div class="userInfo">
          <!--收货人-->
          <div class="label">{{$t('message.consignee')}}:</div>
          <!--请填写收货人姓名-->
          <div class="input" :class="{ error: consigneeErrorText }">
            <input v-model.lazy="consignee" :class="{ 'input-error': consigneeErrorText }" type="text" spellcheck="false" :placeholder="$t('message.consigneeHolder')">
          </div>
          <div class="error-tips" v-show="consigneeErrorText">
          	{{ consigneeErrorText }}
          </div>
          <!--手机号码-->
          <div class="label">{{ $tc('message.phone', 1) }}:</div>
          <!--请输入手机号码-->
          <div class="input" :class="{ error: mobileErrorText }">
            <input v-model.lazy.trim="mobile" :class="{ 'input-error': mobileErrorText }" type="text" :placeholder="$t('message.phoneHolder')">
          </div>
          <div class="error-tips" v-show="mobileErrorText">
            {{ mobileErrorText }}
          </div>
          <!--收货地址-->
          <!-- v-if="!(buyType === 'installment')" -->
          <div class="label">
            {{ $t('message.chooseYourAddress') }}:
            <span class="tip-text">({{$t('message.onlySupport')}})</span>
          </div>
          <!--选择地址-->
          <!-- v-if="!(buyType === 'installment')" -->
          <div class="input" :class="{ error: selectErrorText }">
            <!--<select-city @selet-address="chooseAddress" :province-id="provinceId" :city-id="cityId" :district-id="districtId"></select-city>-->
            <div class="float-left">
              <v-select :selections="provinceSelection" width="75px" :default-value="provinceId" @on-change="selectProvince"></v-select>
            </div>
            <div class="float-left">
              <v-select :selections="citySelection" width="75px" :default-value="cityId" @on-change="selectCity"></v-select>
            </div>
            <div class="float-left">
              <v-select :selections="districtSelection" width="75px" :default-value="districtId" @on-change="selectDistrict"></v-select>
            </div>
          </div>
          <div class="error-tips" v-if="selectErrorText">
          	{{ selectErrorText }}
          </div>
          <!--详细地址-->
          <div class="label">{{ $t('message.detailedAddress') }}:</div>
          <!--请填写详细收货地址，例如街道名称、门牌号、楼层和房间号等信息-->
          <div class="input margin-bottom-12" :class="{ 'error': addressDetailErrorText }">
            <!-- 分期购买 -->
            <v-select :selections="addressSelection" width="361px" @on-change="selectAddress" :default-value="addressDetailId" v-if="buyType === 'installment'"></v-select>
            <!-- 全额购买 -->
            <textarea v-model.lazy="addressDetail" class="testarea" :class="{ 'input-error': addressDetailErrorText }" :placeholder="$t('message.addressHolder')" v-if="buyType === 'full'"></textarea>
            <!-- <textarea v-model.lazy="addressDetail" class="testarea" :class="{ 'input-error': addressDetailErrorText }" :placeholder="$t('message.addressHolder')"></textarea> -->
          </div>
          <!-- 根据选择地址显示学校名称 -->
          <p class="tip-text margin-bottom-24" v-if="schoolName && schoolName !== ''">{{ schoolName }}</p>
          <div class="error-tips" v-if="addressDetailErrorText">
          	{{ addressDetailErrorText }}
          </div>
          <!--设为默认地址-->
          <div class="set-default-location">
            <input type="checkbox" v-model="checked">
            <span>{{ $t('message.asDefaultAddress') }}</span>
          </div>
        </div>
      </div>
      <div class="btn-group">
        <!--保存-->
        <button type="button" class="btn btn-save" @click="save">{{$t('message.save')}}</button>
        <!--取消-->
        <button type="button" class="btn btn-cancel" @click="cancel">{{$t('message.cancel')}}</button>
      </div>
    </div>
  </v-dialog>
</template>

<script>
import VDialog from '@/components/base/VDialog'
import VSelect from '@/components/base/VSelect'

export default {
  name: 'BuyAddressDialog',
  components: {
    VDialog,
    VSelect
  },
  props: {
    content: {
      type: Object
    },
    isNewAdd: {
      type: Number
    },
    // 判断是全额购买还是分期购买 1为全额 2为分期
    switchAddress: {
      type: [Number, String],
      default: 1
    }
  },
  data () {
    return {
      operation: '',
      consignee: '',
      consigneeStatus: 0,
      mobile: '',
      mobileStatus: 0,
      provinceId: '',
      cityId: '',
      districtId: '',
      selectStatus: 0,
      addressDetail: '',
      addressDetailId: '',
      addressDetailStatus: 0,
      checked: '',
      schoolName: '',
      province: [],
      city: [],
      district: [],
      address: [],
      address_province: [],
      address_city: [],
      address_district: [],
      clickCount: 0,
      buyType: this.$route.query.buyType
    }
  },
  computed: {
    // 2:输入内容不能为空
    consigneeErrorText () {
      switch (this.consigneeStatus) {
        case 0:
          return ''
        case 1:
          return ''
        case 2:
          return this.$t('message.inputError')
      }
    },
    // 2:输入内容不能为空
    // 3:手机号码格式错误
    mobileErrorText () {
      switch (this.mobileStatus) {
        case 0:
          return ''
        case 1:
          return ''
        case 2:
          return this.$t('message.phoneErr')
      }
    },
    // 2: 请选择收货地址
    selectErrorText () {
      switch (this.selectStatus) {
        case 0:
          return ''
        case 1:
          return ''
        case 2:
          return this.$t('message.selectAddress')
      }
    },
    // 2:输入内容不能为空
    addressDetailErrorText () {
      switch (this.addressDetailStatus) {
        case 0:
          return ''
        case 1:
          return ''
        case 2:
          return this.$t('message.inputError')
      }
    },
    // 语言
    lang () {
      return window.lang
    },
    // 省的下拉列表
    provinceSelection () {
      let list = this.buyType === 'installment' ? 'province' : 'address_province'
      return [{name: this.$t('message.chooseWhich')}].concat(this[list])
    },
    // 城市的下拉列表
    citySelection () {
      let list = this.buyType === 'installment' ? 'city' : 'address_city'
      return [{name: this.$t('message.chooseWhich')}].concat(this[list])
    },
    // 区的下拉列表
    districtSelection () {
      let list = this.buyType === 'installment' ? 'district' : 'address_district'
      return [{name: this.$t('message.chooseWhich')}].concat(this[list])
    },
    // 详细地址下拉
    addressSelection () {
      return [{name: this.$t('message.chooseWhich')}].concat(this.address)
    },
    // 新增或修改地址传递后台的参数
    postData () {
      let postData = {
        consignee: this.consignee,
        mobile: this.mobile,
        province: this.provinceId,
        city: this.cityId,
        district: this.districtId,
        address_detail: this.addressDetail,
        lang: this.lang,
        pay_type: this.buyType === 'installment' ? 2 : 1,
        open_addr_id: this.addressDetailId
      }
      if (this.operation === 'update') {
        postData.address_id = this.address_id
      }
      return postData
    },
    // 获取语言类型
    languageType () {
      let t = window.localStorage.getItem('thaiPayMallLanguage')
      var languageType
      if (t) {
        if (t === 'cn') {
          languageType = 1
        } else if (t === 'en') {
          languageType = 3
        } else {
          languageType = 2
        }
      } else {
        languageType = 2
      }
      return languageType
    }
    // 获取购买类型: 全额 || 分期
    /*buyType () {
      return this.$route.query.buyType
    }*/
  },
  watch: {
    switchAddress (val) {
      if (val === 1) {
        this.buyType = 'full'
      } else {
        this.buyType = 'installment'
      }
    },
    isNewAdd () {
      console.log('pp')
    },
    consignee () {
      this.checkConsignee()
    },
    mobile () {
      this.checkMobile()
    },
    districtId () {
      if (this.provinceId !== '' && this.cityId !== '' && this.districtId !== '') {
        this.selectStatus = 1
      }
    },
    addressDetail () {
      this.checkAddressDetail()
    }
  },
  methods: {
    // 验证收货人
    checkConsignee () {
      let consignee = this.consignee
      if (/^\s*$/g.test(consignee)) {
        this.consigneeStatus = 2
      } else {
        this.consigneeStatus = 1
      }
    },
    // 验证手机号码
    checkMobile () {
      let mobile = this.mobile
      if (!/^[0][689]\d{8}$/.test(mobile)) {
        this.mobileStatus = 2
      } else {
        this.mobileStatus = 1
      }
    },
    // 验证详细地址
    checkAddressDetail () {
      let addressDetail = this.addressDetail
      if (/^\s*$/g.test(addressDetail)) {
        this.addressDetailStatus = 2
      } else {
        this.addressDetailStatus = 1
      }
    },
    // 选择省级地址
    selectProvince (item) {
      this.provinceId = item.id
      if (this.buyType === 'installment') {
        this.getAddress('city', item.id)
      } else {
        this.getAddress('address_city', item.id)
      }
      this.cityId = ''
      this.districtId = ''
      this.district = []
      this.selectStatus = 0
    },
    // 选择城市级地址
    selectCity (item) {
      if (this.provinceId === '') {
        return
      }
      this.cityId = item.id
      if (this.buyType === 'installment') {
        this.getAddress('district', item.id)
      } else {
        this.getAddress('address_district', item.id)
      }
      this.districtId = ''
      this.selectStatus = 0
    },
    // 选择区域级地址
    selectDistrict (item) {
      if (this.buyType === 'installment') {
        if (this.cityId === '') {
          return
        }
        this.districtId = item.id
        this.getAddress('address', item.id)
        this.addressDetailId = ''
        this.selectStatus = 0
      } else {
        // underfined为 用户选择了 ‘请选择’，并不是对应的地址
        if (item.id !== undefined) {
          this.districtId = item.id
          this.selectStatus = 1
        } else {
          this.selectStatus = 0
        }
      }
    },
    // 选择详细地址
    selectAddress (item) {
      // underfined为 用户选择了 ‘请选择’，并不是对应的地址
      if (item.id !== undefined) {
        this.addressDetailId = item.id
        this.addressDetail = item.name
        this.schoolName = item.note
        this.selectStatus = 1
      } else {
        this.selectStatus = 0
      }
    },
    // 获取选择的地址
    getAddress (type, pid) {
      let func = this.buyType === 'installment' ? 'getAddressItemInstallment' : 'getAddressItemFull'
      this.$ajax[func](type, pid, this.lang).then((res) => {
        if (res.code === 200) {
          this[type] = res.data
        } else if (res.code === 202) {
          this.$store.commit('alert', {
            switch: true,
            alertText: this.$t('message.paramFault')
          })
        }
      }).catch(err => {
        this.$store.commit('alert', {
          switch: true,
          alertText: this.$t('message.errorMessage')
        })
      })
    },
    // 点击保存按钮
    save () {
      if (this.consigneeStatus !== 1) {
        this.consigneeStatus = 2
      }
      if (this.mobileStatus !== 1) {
        this.mobileStatus = 2
      }
      if (this.selectStatus !== 1) {
        this.selectStatus = 2
      }
      if (this.addressDetailStatus !== 1) {
        this.addressDetailStatus = 2
      }
      if (this.consigneeStatus === 1 && this.mobileStatus === 1 && this.selectStatus === 1 && this.addressDetailStatus === 1) {
      //  阻止用户疯狂的点击按钮，导致增加多个相同的地址
        if (this.clickCount === 0) {
          this.clickCount = 1
          if (this.operation === 'update') {
            this.updateAddress()
          } else {
            this.increaseAddress()
          }
        }
      }
    },
    // 增加新地址
    increaseAddress () {
      let data = this.postData
      this.$ajax.setAddress(data).then(res => {
        if (res.code === 200) {
          this.setDefaultAddress(res.data.address_id)
        } else if (res.code === 201) {
          this.$router.push('/login')
        } else if (res.code === 202) {
          this.$store.commit('alert', {
            switch: true,
            alertText: this.$t('message.failToIncreaseAddr')
          })
        } else if (res.code === 203) {
          this.$store.commit('alert', {
            switch: true,
            alertText: this.$t('message.paramFault')
          })
        } else if (res.code === 204) {
          this.$store.commit('alert', {
            switch: true,
            alertText: this.$t('message.mobileInvalid')
          })
        }
      }).catch(err => {
        this.$store.commit('alert', {
          switch: true,
          alertText: this.$t('message.errorMessage')
        })
      })
    },
    // 修改地址
    updateAddress () {
      let data = this.postData
      // 判断添加的是分期 or 全额地址
      // if (this.buyType === 'installment') {
      //   data.pay_type = 2
      // } else {
      //   data.pay_type = 1
      // }
      this.$ajax.reSetAdderss(data).then(res => {
        let paramFault = res.code === 303 || res.code === 305 || res.code === 307 || res.code === 309 || res.code === 311 || res.code === 313 || res.code === 315
        if (res.code === 200) {
          this.setDefaultAddress(this.address_id)
        } else if (res.code === 201) {
          this.$router.push('/login')
        } else if (res.code === 202) {
          this.$store.commit('alert', {
            switch: true,
            alertText: this.$t('message.failToUpdateAddr')
          })
        } else if (paramFault) {
          this.$store.commit('alert', {
            switch: true,
            alertText: this.$t('message.paramFault')
          })
        }
      }).catch(err => {
        this.$store.commit('alert', {
          switch: true,
          alertText: this.$t('message.errorMessage')
        })
      })
    },
    // 设置默认地址
    setDefaultAddress (addressId) {
      if (this.checked === true) {
        this.$ajax.setDefaultAdderss(addressId).then((res) => {
          if (res.code === 200) {
            this.$emit('refresh')
            this.cancel()
          } else if (res.code === 201) {
            this.$router.push('/login')
          } else if (res.code === 202) {
            this.$store.commit('alert', {
              switch: true,
              alertText: this.$t('message.failToSetDefaultAddr')
            })
          }
        }).catch(err => {
          this.$store.commit('alert', {
            switch: true,
            alertText: this.$t('message.errorMessage')
          })
        })
      } else {
        this.$emit('refresh')
        this.cancel()
      }
    },
    // 点击取消按钮
    cancel () {
      this.$emit('close-dialog')
    }
  },
  created () {
    if (this.switchAddress === 1) {
      this.buyType = 'full'
    } else {
      this.buyType = 'installment'
    }
    // 获取省级地址
    if (this.buyType === 'installment') {
      this.getAddress('province', '')
    } else {
      this.getAddress('address_province', '')
    }
    // 判断父组件是否传递content
    if (JSON.stringify(this.content) !== '{}') {
      this.operation = 'update'
      this.address_id = this.content.address_id
      this.consignee = this.content.consignee
      this.mobile = this.content.mobile
      this.addressDetail = this.content.address_detail
      this.addressDetailId = this.content.address_id
      if (this.languageType === 1) { // 中文
        this.schoolName = this.content.note_c
      } else if (this.languageType === 2) { // 泰文
        this.schoolName = this.content.note_t
      } else if (this.languageType === 3) { // 英文
        this.schoolName = this.content.note_e
      }
      // 地址
      this.provinceId = this.content.province_id
      this.cityId = this.content.city_id
      this.districtId = this.content.district_id
      this.addressDetailId = this.content.open_addr_id
      // 获取城市级和区域级地址
      if (this.buyType === 'installment') {
        this.getAddress('city', this.provinceId)
        this.getAddress('district', this.cityId)
        this.getAddress('address', this.districtId)
      } else {
        this.getAddress('address_city', this.provinceId)
        this.getAddress('address_district', this.cityId)
      }
      // 是否为默认地址
      if (this.content.is_default === 1) {
        this.checked = true
      }
    } else {
      this.operation = 'increase'
    }
  }
}
</script>

<style scoped>
.wrap-content {
  background: #ffffff;
  width: 416px;
  padding: 40px;
}

.title {
  line-height: 28px;
  font-size: 20px;
  font-weight: bold;
  text-align: center;
  margin-bottom: 40px;
}

.content {
  width: 434px;
  max-height: 400px;
  overflow-y: auto;
}

.userInfo {
}

.userInfo .label {
  line-height: 20px;
  margin-bottom: 12px;
}

.userInfo .input {
  margin-bottom: 24px;
}

.userInfo .error {
  margin-bottom: 12px;
}

.userInfo .tip-text {
  font-size: 12px;
  color: #A5A5A5;
  letter-spacing: 0;
}

.error-tips {
  margin-bottom: 12px;
}

.margin-bottom-12 {
  margin-bottom: 12px !important;
}

.margin-bottom-24 {
  margin-bottom: 24px !important;
}

.input input {
  width: 416px;
  height: 46px;
  border: 1px solid #d7d7d7;
  border-radius: 2px;
  padding: 0 15px;
  box-sizing: border-box;
}

.input:after {
  content: '';
  display: block;
  width: 0;
  height: 0;
  clear: both;
  visibility: hidden;
}

.input .float-left {
  float: left;
  margin-right: 14px;
}

.input .float-left:last-child {
  margin-right: 0;
}

.textarea-container {
  height: 120px;
}

.testarea {
  width: 416px;
  height: 120px;
  padding: 14px 16px;
  border:1px solid #ccc;
  box-sizing: border-box;
  resize: none;
}

.set-default-location {
  height: 17px;
  line-height: 17px;
  color: #666666;
  font-size: 0;
}

.set-default-location input {
  width: 16px;
  height: 16px;
  float: left;
 margin-top: 1px;
}

.set-default-location span {
  font-size: 12px;
  margin-left: 12px;
}

.btn-group {
  font-size: 0;
  text-align: center;
  margin-top: 32px;
}

.btn {
  cursor: pointer;
  width: 150px;
  height: 44px;
  border-radius: 2px;
}

.btn-save {
  border: 0;
  background-color: #ff600a;
  color: #fff;
}

.btn-cancel {
  border: 1px solid #d7d7d7;
  color: #a5a5a5;
  background-color: #fff;
  margin-left: 16px;
}
</style>
